////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DeviceIdSharedPrefTools;
import cc.telecomdigital.tdstock.ExceptionHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.ProgressDialog;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.Activity_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.TDStockReqFreeTrial.ITDStockReqFreeTrial_Result;
import cc.telecomdigital.tdstock.Services.TDStockReqFreeTrial.TDStockReqFreeTrial_Result;

/**
 * login screen entry
 * @author haibo
 * @desc modify by ouyangzhihui
 */
public class DeclareTrialActivity extends Activity_Framework implements OnClickListener
{
	protected static final String	ACTION_INSTALL_SHORTCUT	= "com.android.launcher.action.INSTALL_SHORTCUT";
	protected static final String	EXTRA_SHORTCUT_DUPLICATE	= "duplicate";

	private Button				_btnReturn;
	private Button				_btnConfirm;

	private Button				_trial_realtime_phone_address;
	private ScrollView			_scrollview;

	private EditText			_edtPhone;
	private EditText			_edtName;
	private EditText			_edtEmail;
	private static String		TAG					= DeclareTrialActivity.class.getSimpleName();

	protected static String		_menu_exit_app_res		= null;
	protected static String		_menu_gen_launcher_res	= null;

	protected static String		_progressTitle_res		= null;
	protected static String		_progressLinking_res	= null;

	public static final int		EXIT_APP				= Menu.FIRST;
	public static final int		CREATE_LAUNCHER		= Menu.FIRST + 1;

	private Context			_context;

	private void switchBackActivity()
	{
		Intent intent = new Intent(getApplicationContext(), RealtimeStockActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		//startActivity(intent);
		SwitchFreeActivity(RealtimeStockActivity.class , intent);
		this.finish();
	}
	
	@Override
	public void onClick(View v)
	{
		if (v == _btnReturn)
		{
			switchBackActivity();
		}
		else if (v == _btnConfirm)
		{

			if (!isValidMobileNumber())
			{
				new CustomizeDialog(this, getResources().getString(R.string.info), "電話號碼錯誤，請重新輸入", 
						getResources().getString(R.string.ok)).show();
				return;
			}

			TrialRegisterAuth(_edtName.getText().toString(), _edtPhone.getText().toString(), _edtEmail.getText().toString());
			
//			new RegisterAsyncTask(DeclareTrialActivity.this.getMyOwnContext()).execute(/*deviceId, */
//					phone_address_code[phone_address_code_id], _edtPhone.getText().toString(), 
//					_edtName.getText().toString(),
//					_edtEmail.getText().toString());
		}
	}

	private void forwardToVerifyActiveCode()
	{
		Intent intent = new Intent(getApplicationContext(),
				VerifyActiveCodeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |  Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		//startActivity(intent);
		
		SwitchFreeActivity(VerifyActiveCodeActivity.class , intent);
	}

	private String[]	phone_address_longtxt	= new String[] { "香港 - 852",
			"澳門 - 853", "中國國內 - 86"			};
	private String[]	phone_address_txt		= new String[] { "香港 852",
			"澳門 853", "中國 86"				};

	private String[] phone_address_code = new String[] { "hk", "macau", "cn" };
	private int phone_address_code_id = 0;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		ExceptionHandler.register(this);
		setContentView(R.layout.declaretrial);
		
		_btnReturn = (Button) findViewById(R.id.btn_returnpre);
		_btnConfirm = (Button) findViewById(R.id.btn_confirm);

		_edtPhone = (EditText) findViewById(R.id.trial_realtime_phone);
		_edtEmail = (EditText) findViewById(R.id.trial_realtime_email);
		_edtName = (EditText) findViewById(R.id.trial_realtime_name);

		_trial_realtime_phone_address = (Button) findViewById(R.id.trial_realtime_phone_address);
		_trial_realtime_phone_address.setText(phone_address_txt[0]);
		_trial_realtime_phone_address
				.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						new AlertDialog.Builder(DeclareTrialActivity.this)
								.setTitle("電話號碼所屬地區：")
								.setItems(
										phone_address_longtxt,
										new DialogInterface.OnClickListener()
										{
											@Override
											public void onClick(
													DialogInterface dialog,
													int which)
											{
												_trial_realtime_phone_address
														.setText(phone_address_txt[which]);
												phone_address_code_id = which;
											}
										}).show();
					}
				});

		_btnReturn.setOnClickListener(this);
		_btnConfirm.setOnClickListener(this);
		_menu_exit_app_res = getResources().getString(R.string.app_exit);
		_menu_gen_launcher_res = getResources().getString(
				R.string.app_launcher);

		_progressTitle_res = getResources().getString(
				R.string.loading_indicator);
		_progressLinking_res = getResources().getString(
				R.string.linking_mesgr);

		_context = this;

		_scrollview = (ScrollView) findViewById(R.id.scrollview);
		_scrollview.setScrollbarFadingEnabled(true);
	}

	protected Context getMyOwnContext()
	{
		return _context;
	}

	protected synchronized void handleExitApplication()
	{
		new AlertDialog.Builder(this).setTitle(
				getResources().getString(R.string.info)).setMessage(
				getResources().getString(R.string.application_exit_tips))
				.setIcon(
						getResources().getDrawable(
								R.drawable.help_menu_icon))
				.setPositiveButton(getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener()
						{
							public void onClick(
									DialogInterface dialoginterface,
									int i)
							{
								((ITDLApplication) getApplicationContext())
										.setExitApp(true);
								exitApp();
							}
						}).setNegativeButton(
						getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,
									int whichButton)
							{

							}
						}).show();

	}

	public void exitApp()
	{
		finish();
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
	}

	protected synchronized void genLauncher()
	{
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		// intent2.setComponent(new ComponentName(this.getPackageName(),    ".activity.LoginActivity"));    
		intent2.setComponent(new ComponentName(this.getPackageName(),
				".activity.SplashActivity"));

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(this,
						R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext())
						.setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume()
	{
		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
		/*else {
			Class<?> currentActivityClass = ((ITDLApplication)getApplicationContext()).getCurrentActivityClass();
			if(currentActivityClass != null) {
				Intent intent = new Intent(getApplicationContext(), currentActivityClass);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);   //continuing to get the last activity
			}
		}*/

		super.onResume();
	}

	private boolean isValidMobileNumber()
	{
		boolean result = _edtPhone.getText().toString().length() >= 8; //simply check
		return result;
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();

		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
	}
	
	private ProgressDialog _progressDialog;
	
	private void ShowProgressDialog()
	{
		if(_progressDialog == null)
			_progressDialog = new ProgressDialog(DeclareTrialActivity.this, Html.fromHtml("正在初始化數據並連接至伺服器<br/>請稍候...").toString());
		_progressDialog.show();
	}
	
	private void DismissProgressDialog()
	{
		if(_progressDialog != null)
		{
			_progressDialog.dismiss();
			_progressDialog = null;
		}
	}
	
	private void TrialRegisterAuth(String iUserName, String iMobileNumber, String iEmail)
	{
		ShowProgressDialog(); //show
		
		String deviceId;
		deviceId = DeviceIdSharedPrefTools.getDeviceId();
		
		if(deviceId.trim().length() != SystemInfo.DEVICE_ID_LENGTH)
		{
			String[] deviceId_auth = SystemInfo.GetDeviceIdAuthWifiMac(DeclareTrialActivity.this);
			if(SystemInfo.FAILED_CODE.equals(deviceId_auth[0])) // failed
			{
				DismissProgressDialog(); //dismiss
				
				if(deviceId_auth[2].trim().length() < 1)
					deviceId_auth[2] = "操作失敗，請稍後再试。";
				
				new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info),
						deviceId_auth[2], getResources().getString(R.string.ok))
				{
					@Override
					public void onClick(View v)
					{
						if(v == okButton)
						{
//							switchBackActivity();
							dismissAll();
							((ITDLApplication) getApplicationContext()).setExitApp(true);
							exitApp();
						}
					}
				}.show();
				return;
			}
		}
		
		appHost.LS_RequestFreeTrial(iUserName, iMobileNumber, iEmail, new ITDStockReqFreeTrial_Result()
		{
			@Override
			public void TDStockReqFreeTrail_Response(TDStockReqFreeTrial_Result iResult)
			{
				DismissProgressDialog(); //dismiss
				ResetKey();
				
				String errorMsg = "";
				if (iResult.statusCode.equals("0"))
				{
					if (iResult.errorMessage.trim().length() >= 1)
					{
						new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info), iResult.errorMessage, getResources().getString(R.string.ok))
						{
							@Override
							public void onClick(View v)
							{
								if(v == okButton) 
								{
									dismiss(); 
									
									forwardToVerifyActiveCode();
								}
							}
						}.show();
					}
					return;
				}
				else if (iResult.errorMessage.trim().length() >= 1)
				{
					errorMsg = iResult.errorMessage;
				}
				else
				{
					errorMsg = "登記失敗!";
				}
				new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info), errorMsg, getResources().getString(R.string.ok)).show();
			}
		});
	}
	
//	private int count = 0;
//	private class RegisterAsyncTask extends BaseAsyncTask
//	{
//		public RegisterAsyncTask(Context context)
//		{
//			super(context);
//		}
//
//		private boolean	isExceptionHappened;
//		private String[]	auth_info;
//		private ProgressDialog _dialog;
////		private String deviceId;
//		private String[] deviceId_auth;
//		//		private final ProgressDialog dialog = new ProgressDialog(DeclareTrialActivity.this);
//
//		@Override
//		protected Void doInBackground(String... params)
//		{
//			try
//			{
//			/*	TDStockLog.d(TAG, "params[0]="+params[0]+" , params[1]="+params[1]+" , params[2]="+params[2]+" , params[3]="+params[3]+" , params[4]="+params[4]);
//				TrialRegisterAuth auth = new TrialRegisterAuth(params[0],
//						params[1], params[2], params[3], params[4]);*/
//				
//				String deviceId = _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
//				
//				if(deviceId.trim().length() < 2)
//				{
//					deviceId_auth = SystemInfo.GetDeviceIdAuthWifiMac(DeclareTrialActivity.this);
//				}
//				else
//				{
//					deviceId_auth = new String[3];
//					deviceId_auth[0] = SystemInfo.SUCCESS_CODE;
//					deviceId_auth[1] = deviceId;
//					deviceId_auth[2] = "";
//				}
//				
//				if(SystemInfo.SUCCESS_CODE.equals(deviceId_auth[0]))
//				{
////					String edevinfo = SystemInfo.getDeviceExtraInfo(DeclareTrialActivity.this); 
//
//					TrialRegisterAuth auth = new TrialRegisterAuth(deviceId_auth[1],
//							params[0], params[1], params[2], params[3]/*, 
//							edevinfo, _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "")*/);
//					
//					auth_info = auth.getAuthentication();
//				}
//				
//				/*
//				deviceId = SystemInfo.getDeviceId(DeclareTrialActivity.this);
//				
//				// 是否拿到mac address
//				if(SystemInfo.EMPTY_WIFI_MAC_ADDRESS.equals(SystemInfo.current_wifi_mac_address))
//				{
//					return null;
//				}
//				
//				String edevinfo = SystemInfo.getDeviceExtraInfo(DeclareTrialActivity.this); 
//
//				TrialRegisterAuth auth = new TrialRegisterAuth(deviceId,
//						params[0], params[1], params[2], params[3], 
//						edevinfo, _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, deviceId));
//				
//				auth_info = auth.getAuthentication();
//				
//				TDStockLog.d(TAG, "params[0]="+params[0]+" , params[1]="+params[1]+" , params[2]="+params[2]+" , params[3]="+params[3]);
//				for (int i = 0; i < auth_info.length; i++)
//				{
//					TDStockLog.d("TAG", "declare trial onclick to doInbackground auth_info[" + i + "]=" + auth_info[i]);
//				}*/
//			}
//			catch (Exception e)
//			{
//				TDStockLog.e(TAG, e.getMessage() == null ? " unkonw exception in RegisterAsyncTask! "  : e.getMessage());
//				isExceptionHappened = true;
//			}
//			return null;
//		}
//
//		@Override
//		protected void onPostExecute(Void result)
//		{
//			super.onPostExecute(result);
//			if(_dialog != null)
//				_dialog.dismiss();
//			/*----------------------------------------*/
//			if(SystemInfo.FAILED_CODE.equals(deviceId_auth[0])) // failed
//			{
//				if(deviceId_auth[2].trim().length() < 1)
//					deviceId_auth[2] = "操作失敗，請稍後再试。";
//				new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info),
//						deviceId_auth[2], getResources().getString(R.string.ok))
//				{
//					@Override
//					public void onClick(View v)
//					{
//						if(v == okButton)
//						{
////							switchBackActivity();
//							dismissAll();
//							((ITDLApplication) getApplicationContext()).setExitApp(true);
//							exitApp();
//						}
//					}
//				}.show();
//				return;
//			}
//			
//			/*if(SystemInfo.EMPTY_WIFI_MAC_ADDRESS.equals(SystemInfo.current_wifi_mac_address))
//			{
//				if(count < 2)
//				{
//					new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info),
//							"操作失敗，請重試！", getResources().getString(R.string.ok)).show();
//				}
//				else
//				{
//					new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info),
//							"操作失敗，請退出后再重试！", getResources().getString(R.string.ok))
//					{
//						@Override
//						public void onClick(View v)
//						{
//							if(v == okButton)
//							{
//								switchBackActivity();
//							}
//						}
//					}.show();
//				}
//				count++;
//				return;
//			}*/
//			/*----------------------------------------*/
//			
//			try
//			{
//				ResetKey();
//
//				if (this.isCancelled() || isExceptionHappened || auth_info == null)
//				{
//					return;
//				}
//
//				String errorMsg = "";
//				TDStockLog.d(TAG, "auth0"+auth_info[0]);
//				TDStockLog.d(TAG, "auth1"+auth_info[1]);
//				if (auth_info[0].equals("0"))
//				{
//					if (auth_info[1].trim().length() >= 1)
//					{
//						new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info), auth_info[1], getResources().getString(R.string.ok))
//						{
//							@Override
//							public void onClick(View v)
//							{
//								if(v == okButton) 
//								{
//									dismiss(); 
//									
//									// 已經發送過驗證碼給客戶
//									/*_prefs.edit().putBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE, true).commit();
//									
//									// 如果未存储 deviceid 则将其保存起来
//									String pdeviceId = _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
//									if(pdeviceId.length() <= 1)
//									{
//										_prefs.edit().putString(CommonDefn.PREFERENCE_DEVICE_ID, deviceId).commit();
//									}*/
//									
//									forwardToVerifyActiveCode();
//								}
//							}
//						}.show();
//					}
//					return;
//				}
//				else if (auth_info[1].trim().length() >= 1)
//				{
//					errorMsg = auth_info[1];
//				}
//				else
//				{
//					errorMsg = "登記失敗!";
//				}
//				new CustomizeDialog(DeclareTrialActivity.this, getResources().getString(R.string.info), errorMsg, getResources().getString(R.string.ok)).show();
//			}
//			catch (Exception e)
//			{
//			}
//			finally
//			{
//			}
//		}
//
//		@Override
//		protected void onPreExecute()
//		{
//			super.onPreExecute();
//			_dialog = new ProgressDialog(DeclareTrialActivity.this, Html.fromHtml("正在初始化數據並連接至伺服器<br/>請稍候...").toString());
//			_dialog.show();
//		}
//	}
	
	private void ResetKey()
	{
		try
		{
			Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			InputMethodManager imm = (InputMethodManager) service;
			if (_edtPhone.isFocused())
				imm.hideSoftInputFromWindow(_edtPhone
						.getWindowToken(), 0); //auto close the soft keyboard after finishing input.
			if (_edtName.isFocused())
				imm.hideSoftInputFromWindow(_edtName
						.getWindowToken(), 0); //auto close the soft keyboard after finishing input.
			if (_edtEmail.isFocused())
				imm.hideSoftInputFromWindow(_edtEmail
						.getWindowToken(), 0); //auto close the soft keyboard after finishing input.
			Thread.yield();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		TDStockLog.d(TAG, "destory!");
	}
	
}
